package com.lyz.dz.des.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;

import com.lyz.dz.des.utile.AjaxJson;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@ControllerAdvice
/**
 * @author:cahrzhan
 */
public class globleExcption {
    @ModelAttribute
    public void get(HttpServletRequest request) throws IOException {

    }
    @ResponseBody
    @ExceptionHandler
    public AjaxJson handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        // 不同异常返回不同状态码
        AjaxJson aj = null;
        if (e instanceof NotLoginException) {	// 如果是未登录异常
            NotLoginException ee = (NotLoginException) e;
            aj = AjaxJson.getNotLogin().setMsg(ee.getMessage());
        } else if(e instanceof NotRoleException) {		// 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            aj = AjaxJson.getNotJur("无此角色：" + ee.getRole());
        } else if(e instanceof NotPermissionException) {	// 如果是权限异常
            NotPermissionException ee = (NotPermissionException) e;
            aj = AjaxJson.getNotJur("无此权限：" + ee.getCode());
        }else if(e instanceof BindException) {	// 如果是权限异常
            BindException ee = (BindException) e;
            List<FieldError> fieldErrors = ee.getBindingResult().getFieldErrors();
            StringBuilder stringBuilder = new StringBuilder();
            for (FieldError fe :
                    fieldErrors) {
                stringBuilder.append(fe.getDefaultMessage());

                stringBuilder.append("-");
            }
            aj = AjaxJson.getError( stringBuilder.toString());
        }  else {	// 普通异常, 输出：500 + 异常信息

//            aj = AjaxJson.getError(e.getMessage());
            aj = AjaxJson.getError(e.toString());
        }

        // 返回给前端
        return aj;

        // 输出到客户端
//		response.setContentType("application/json; charset=utf-8"); // http说明，我要返回JSON对象
//		response.getWriter().print(new ObjectMapper().writeValueAsString(aj));
    }
}
